<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryRef" :inline="true" v-show="showSearch" label-width="68px">
      <el-form-item label="项目名称" prop="projectName">
        <el-input
          v-model="queryParams.projectName"
          placeholder="请输入项目名称"
          clearable
          @keyup.enter="handleQuery"
        />
      </el-form-item>
      <el-form-item label="任务名称" prop="taskName">
        <el-input
          v-model="queryParams.taskName"
          placeholder="请输入任务名称"
          clearable
          @keyup.enter="handleQuery"
        />
      </el-form-item>
      <el-form-item label="填报人" prop="userName">
        <el-input
          v-model="queryParams.userName"
          placeholder="请输入填报人姓名"
          clearable
          @keyup.enter="handleQuery"
        />
      </el-form-item>
      <el-form-item label="工时日期" prop="workDate">
        <el-date-picker clearable
          v-model="queryParams.workDate"
          type="date"
          value-format="YYYY-MM-DD"
          placeholder="请选择工时日期">
        </el-date-picker>
      </el-form-item>
      <!-- <el-form-item label="工时数" prop="hours">
        <el-input
          v-model="queryParams.hours"
          placeholder="请输入工时数"
          clearable
          @keyup.enter="handleQuery"
        />
      </el-form-item> -->
      <el-form-item label="是否加班" prop="isOvertime">
        <el-select v-model="queryParams.isOvertime" placeholder="请选择是否加班" clearable style="width: 180px">
          <el-option label="正常" :value="0" />
          <el-option label="加班" :value="1" />
        </el-select>
      </el-form-item>
      <!-- <el-form-item label="加班工时" prop="overtimeHours">
        <el-input
          v-model="queryParams.overtimeHours"
          placeholder="请输入加班工时"
          clearable
          @keyup.enter="handleQuery"
        />
      </el-form-item> -->
      <el-form-item label="归档状态" prop="finalStatus">
        <el-select v-model="queryParams.finalStatus" placeholder="请选择归档状态" clearable style="width: 200px">
          <el-option
            v-for="dict in final_status"
            :key="dict.value"
            :label="dict.label"
            :value="dict.value"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="审批步骤" prop="approvalStep">
        <el-select v-model="queryParams.approvalStep" placeholder="请选择审批步骤" clearable style="width: 180px">
          <el-option label="第1级（主管）" :value="1" />
          <el-option label="第2级（销售）" :value="2" />
        </el-select>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="Search" @click="handleQuery">搜索</el-button>
        <el-button icon="Refresh" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
          type="primary"
          plain
          icon="Plus"
          @click="handleAdd"
          v-hasPermi="['erp:worklog:add']"
        >新增</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="success"
          plain
          icon="Edit"
          :disabled="single"
          @click="handleUpdate"
          v-hasPermi="['erp:worklog:edit']"
        >修改</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="danger"
          plain
          icon="Delete"
          :disabled="multiple"
          @click="handleDelete"
          v-hasPermi="['erp:worklog:remove']"
        >删除</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="warning"
          plain
          icon="Download"
          @click="handleExport"
          v-hasPermi="['erp:worklog:export']"
        >导出</el-button>
      </el-col>
      <right-toolbar v-model:showSearch="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table 
      v-loading="loading" 
      :data="worklogList" 
      @selection-change="handleSelectionChange"
      class="worklog-table"
      stripe
      border
      :header-cell-style="{ background: '#f5f7fa', color: '#606266', fontWeight: '600' }"
    >
      <el-table-column type="selection" width="55" align="center" />
      <el-table-column label="ID" align="center" prop="id" width="80" />
      <el-table-column label="项目" align="center" prop="projectName" width="150" show-overflow-tooltip>
        <template #default="scope">
          <div class="project-info">
            <el-icon class="project-icon"><Folder /></el-icon>
            <span>{{ scope.row.projectName || '暂无' }}</span>
          </div>
        </template>
      </el-table-column>
      <el-table-column label="任务" align="center" prop="taskName" width="150" show-overflow-tooltip>
        <template #default="scope">
          <div class="task-info">
            <el-icon class="task-icon"><Document /></el-icon>
            <span>{{ scope.row.taskName || '暂无' }}</span>
          </div>
        </template>
      </el-table-column>
      <el-table-column label="填报人" align="center" prop="userName" width="120">
        <template #default="scope">
          <div class="user-info" v-if="scope.row.userName">
            <el-avatar :size="24" class="user-avatar">
              <el-icon><User /></el-icon>
            </el-avatar>
            <span class="user-name">{{ scope.row.userName }}</span>
          </div>
          <span v-else class="text-muted">暂无</span>
        </template>
      </el-table-column>
      <el-table-column label="工时日期" align="center" prop="workDate" width="120">
        <template #default="scope">
          <div class="date-info" v-if="scope.row.workDate">
            <el-icon class="date-icon"><Calendar /></el-icon>
            <span>{{ parseTime(scope.row.workDate, '{y}-{m}-{d}') }}</span>
          </div>
          <span v-else class="text-muted">暂无</span>
        </template>
      </el-table-column>
      <el-table-column label="工时数" align="center" prop="hours" width="100">
        <template #default="scope">
          <el-tag type="primary" effect="plain" size="small" v-if="scope.row.hours">
            {{ scope.row.hours }}h
          </el-tag>
          <span v-else class="text-muted">暂无</span>
        </template>
      </el-table-column>
      <el-table-column label="是否加班" align="center" prop="isOvertime" width="100">
        <template #default="scope">
          <el-tag :type="scope.row.isOvertime ? 'warning' : 'info'" effect="plain" size="small">
            {{ scope.row.isOvertime ? '加班' : '正常' }}
          </el-tag>
        </template>
      </el-table-column>
      <el-table-column label="加班工时" align="center" prop="overtimeHours" width="100">
        <template #default="scope">
          <el-tag type="warning" effect="plain" size="small" v-if="scope.row.overtimeHours">
            {{ scope.row.overtimeHours }}h
          </el-tag>
          <span v-else class="text-muted">0h</span>
        </template>
      </el-table-column>
      <el-table-column label="工作内容" align="left" prop="content" min-width="200" show-overflow-tooltip>
        <template #default="scope">
          <div class="content-info" v-if="scope.row.content">
            <el-icon class="content-icon"><Reading /></el-icon>
            <span class="content-text" v-html="scope.row.content"></span>
          </div>
          <span v-else class="text-muted">暂无</span>
        </template>
      </el-table-column>
      <el-table-column label="归档状态" align="center" prop="finalStatus" width="140">
        <template #default="scope">
          <dict-tag :options="final_status" :value="scope.row.finalStatus"/>
        </template>
      </el-table-column>
      <el-table-column label="审批步骤" align="center" prop="approvalStep" width="100">
        <template #default="scope">
          <el-tag type="info" effect="plain" size="small" v-if="scope.row.approvalStep">
            第{{ scope.row.approvalStep }}级
          </el-tag>
          <span v-else class="text-muted">暂无</span>
        </template>
      </el-table-column>
      <el-table-column label="操作" align="center" width="150" fixed="right">
        <template #default="scope">
          <el-button 
            link 
            type="primary" 
            icon="Edit" 
            @click="handleUpdate(scope.row)" 
            v-hasPermi="['erp:worklog:edit']"
            class="action-btn"
          >
            修改
          </el-button>
          <el-button 
            link 
            type="danger" 
            icon="Delete" 
            @click="handleDelete(scope.row)" 
            v-hasPermi="['erp:worklog:remove']"
            class="action-btn"
          >
            删除
          </el-button>
        </template>
      </el-table-column>
    </el-table>
    
    <pagination
      v-show="total>0"
      :total="total"
      v-model:page="queryParams.pageNum"
      v-model:limit="queryParams.pageSize"
      @pagination="getList"
    />

    <!-- 添加或修改工时对话框 -->
    <el-dialog :title="title" v-model="open" width="500px" append-to-body>
      <el-form ref="worklogRef" :model="form" :rules="rules" label-width="100px">
        <!-- 新增时的必填信息 -->
        <div v-if="!form.id">
          <el-row :gutter="20">
            <el-col :span="12">
              <el-form-item label="项目ID" prop="projectId">
                <el-input v-model="form.projectId" placeholder="请输入项目ID" />
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="任务ID" prop="taskId">
                <el-input v-model="form.taskId" placeholder="请输入任务ID" />
              </el-form-item>
            </el-col>
          </el-row>
          <el-row :gutter="20">
            <el-col :span="12">
              <el-form-item label="填报人ID" prop="userId">
                <el-input v-model="form.userId" placeholder="请输入填报人ID" />
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="工时日期" prop="workDate">
                <el-date-picker 
                  clearable
                  v-model="form.workDate"
                  type="date"
                  value-format="YYYY-MM-DD"
                  placeholder="请选择工时日期"
                  style="width: 100%">
                </el-date-picker>
              </el-form-item>
            </el-col>
          </el-row>
        </div>

        <!-- 可编辑字段 -->
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="工时数" prop="hours">
              <el-input-number 
                v-model="form.hours" 
                placeholder="请输入工时数"
                :min="0"
                :max="24"
                :precision="2"
                style="width: 100%" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="是否加班" prop="isOvertime">
              <el-select v-model="form.isOvertime" placeholder="请选择是否加班" style="width: 100%">
                <el-option label="正常" :value="0" />
                <el-option label="加班" :value="1" />
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="加班工时" prop="overtimeHours">
              <el-input-number 
                v-model="form.overtimeHours" 
                placeholder="请输入加班工时"
                :min="0"
                :max="24"
                :precision="2"
                :disabled="!form.isOvertime"
                style="width: 100%" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="归档状态" prop="finalStatus">
              <el-select v-model="form.finalStatus" placeholder="请选择归档状态" style="width: 100%">
                <el-option
                  v-for="dict in final_status"
                  :key="dict.value"
                  :label="dict.label"
                  :value="dict.value"
                />
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>
        <el-form-item label="工作内容">
          <el-input 
            v-model="form.content" 
            type="textarea" 
            :rows="4" 
            placeholder="请输入工作内容" 
            maxlength="500" 
            show-word-limit
          />
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button type="primary" @click="submitForm">确 定</el-button>
          <el-button @click="cancel">取 消</el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script setup name="Worklog">
import { listWorklog, getWorklog, delWorklog, addWorklog, updateWorklog } from "@/api/erp/worklog"
import { Document, User, Calendar, Folder, Reading } from '@element-plus/icons-vue'

const { proxy } = getCurrentInstance()
const { final_status } = proxy.useDict('final_status')

const worklogList = ref([])
const open = ref(false)
const loading = ref(true)
const showSearch = ref(true)
const ids = ref([])
const single = ref(true)
const multiple = ref(true)
const total = ref(0)
const title = ref("")

const data = reactive({
  form: {},
  queryParams: {
    pageNum: 1,
    pageSize: 10,
    projectId: null,
    projectName: null,
    taskId: null,
    taskName: null,
    userId: null,
    userName: null,
    workDate: null,
    hours: null,
    isOvertime: null,
    overtimeHours: null,
    content: null,
    finalStatus: null,
    approvalStep: null,
  },
  rules: {
    // 新增时的必填验证
    projectId: [
      { required: true, message: "项目ID不能为空", trigger: "blur" }
    ],
    taskId: [
      { required: true, message: "任务ID不能为空", trigger: "blur" }
    ],
    userId: [
      { required: true, message: "填报人ID不能为空", trigger: "blur" }
    ],
    workDate: [
      { required: true, message: "工时日期不能为空", trigger: "blur" }
    ],
    // 可编辑字段的验证
    hours: [
      { required: true, message: "工时数不能为空", trigger: "blur" },
      { type: 'number', min: 0, max: 24, message: '工时数必须在0-24之间', trigger: 'blur' }
    ],
    isOvertime: [
      { required: true, message: "请选择是否加班", trigger: "change" }
    ],
    overtimeHours: [
      { type: 'number', min: 0, max: 24, message: '加班工时必须在0-24之间', trigger: 'blur' }
    ]
  }
})

const { queryParams, form, rules } = toRefs(data)

/** 查询工时列表 */
function getList() {
  loading.value = true
  listWorklog(queryParams.value).then(response => {
    worklogList.value = response.rows
    total.value = response.total
    loading.value = false
  })
}

// 取消按钮
function cancel() {
  open.value = false
  reset()
}

// 表单重置
function reset() {
  form.value = {
    id: null,
    projectId: null,
    projectName: null,
    taskId: null,
    taskName: null,
    userId: null,
    userName: null,
    workDate: null,
    hours: null,
    isOvertime: 0,
    overtimeHours: null,
    content: null,
    finalStatus: null,
    approvalStep: null,
    createTime: null,
    updateTime: null
  }
  proxy.resetForm("worklogRef")
}

/** 搜索按钮操作 */
function handleQuery() {
  queryParams.value.pageNum = 1
  getList()
}

/** 重置按钮操作 */
function resetQuery() {
  proxy.resetForm("queryRef")
  handleQuery()
}

// 多选框选中数据
function handleSelectionChange(selection) {
  ids.value = selection.map(item => item.id)
  single.value = selection.length != 1
  multiple.value = !selection.length
}

/** 新增按钮操作 */
function handleAdd() {
  reset()
  open.value = true
  title.value = "添加工时"
}

/** 修改按钮操作 */
function handleUpdate(row) {
  reset()
  const _id = row.id || ids.value
  getWorklog(_id).then(response => {
    form.value = response.data
    open.value = true
    title.value = "修改工时"
  })
}

/** 提交按钮 */
function submitForm() {
  proxy.$refs["worklogRef"].validate(valid => {
    if (valid) {
      // 验证加班逻辑
      if (form.value.isOvertime === 1 && (!form.value.overtimeHours || form.value.overtimeHours <= 0)) {
        proxy.$modal.msgWarning("选择加班时，加班工时必须大于0")
        return
      }
      
      if (form.value.id != null) {
        // 修改时只提交可编辑字段
        const editableData = {
          id: form.value.id,
          hours: form.value.hours,
          isOvertime: form.value.isOvertime,
          overtimeHours: form.value.overtimeHours,
          content: form.value.content,
          finalStatus: form.value.finalStatus
        }
        updateWorklog(editableData).then(response => {
          proxy.$modal.msgSuccess("修改成功")
          open.value = false
          getList()
        })
      } else {
        addWorklog(form.value).then(response => {
          proxy.$modal.msgSuccess("新增成功")
          open.value = false
          getList()
        })
      }
    }
  })
}

/** 删除按钮操作 */
function handleDelete(row) {
  const _ids = row.id || ids.value
  proxy.$modal.confirm('是否确认删除工时编号为"' + _ids + '"的数据项？').then(function() {
    return delWorklog(_ids)
  }).then(() => {
    getList()
    proxy.$modal.msgSuccess("删除成功")
  }).catch(() => {})
}

/** 导出按钮操作 */
function handleExport() {
  proxy.download('erp/worklog/export', {
    ...queryParams.value
  }, `worklog_${new Date().getTime()}.xlsx`)
}

getList()
</script>

<style scoped>
/* 表格样式优化 */
.worklog-table {
  border-radius: 8px;
  overflow: hidden;
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
}

.worklog-table :deep(.el-table__body-wrapper) {
  border-radius: 0 0 8px 8px;
}

.worklog-table :deep(.el-table__header-wrapper) {
  border-radius: 8px 8px 0 0;
}

.worklog-table :deep(.el-table__row) {
  transition: all 0.3s ease;
}

.worklog-table :deep(.el-table__row:hover) {
  background-color: #f8f9fa !important;
  transform: translateY(-1px);
  box-shadow: 0 4px 8px rgba(0, 0, 0, 0.1);
}

/* 项目信息样式 */
.project-info {
  display: flex;
  align-items: center;
  gap: 8px;
  justify-content: center;
}

.project-icon {
  color: #409eff;
  font-size: 16px;
}

/* 任务信息样式 */
.task-info {
  display: flex;
  align-items: center;
  gap: 8px;
  justify-content: center;
}

.task-icon {
  color: #67c23a;
  font-size: 16px;
}

/* 用户信息样式 */
.user-info {
  display: flex;
  align-items: center;
  gap: 8px;
  justify-content: center;
}

.user-avatar {
  background-color: #e6f7ff;
  color: #1890ff;
  border: 1px solid #b3d8ff;
}

.user-name {
  font-size: 13px;
  color: #303133;
  font-weight: 500;
}

/* 日期信息样式 */
.date-info {
  display: flex;
  align-items: center;
  gap: 4px;
  justify-content: center;
}

.date-icon {
  color: #67c23a;
  font-size: 14px;
}

/* 内容信息样式 */
.content-info {
  display: flex;
  align-items: flex-start;
  gap: 8px;
}

.content-icon {
  color: #909399;
  font-size: 14px;
  flex-shrink: 0;
  margin-top: 2px;
}

.content-text {
  color: #606266;
  font-size: 13px;
  line-height: 1.4;
  overflow: hidden;
  text-overflow: ellipsis;
  display: -webkit-box;
  -webkit-line-clamp: 2;
  line-clamp: 2;
  -webkit-box-orient: vertical;
}

/* 暂无文本样式 */
.text-muted {
  color: #c0c4cc;
  font-size: 12px;
  font-style: italic;
}

/* 操作按钮样式 */
.action-btn {
  margin: 0 2px;
  font-size: 12px;
  padding: 4px 8px;
}

.action-btn:hover {
  transform: translateY(-1px);
  box-shadow: 0 2px 4px rgba(0, 0, 0, 0.1);
}

/* 状态标签优化 */
.worklog-table :deep(.el-tag) {
  border-radius: 12px;
  font-weight: 500;
}

/* 对话框样式优化 */
.el-dialog__body {
  padding: 20px 30px;
}

.el-form-item {
  margin-bottom: 18px;
}

.el-form-item__label {
  font-weight: 500;
  color: #606266;
}

.el-input[readonly] .el-input__inner {
  background-color: #f5f7fa;
  color: #909399;
  cursor: not-allowed;
}

.el-switch {
  --el-switch-on-color: #67c23a;
  --el-switch-off-color: #dcdfe6;
}


/* 响应式设计 */
@media (max-width: 768px) {
  .worklog-table :deep(.el-table__header-wrapper),
  .worklog-table :deep(.el-table__body-wrapper) {
    font-size: 12px;
  }
  
  .user-info {
    flex-direction: column;
    gap: 4px;
  }
  
  .project-info {
    flex-direction: column;
    gap: 4px;
  }
  
  .task-info {
    flex-direction: column;
    gap: 4px;
  }
  
  .content-info {
    flex-direction: column;
    gap: 4px;
    align-items: flex-start;
  }
  
  .el-dialog {
    width: 95% !important;
    margin: 5vh auto;
  }
  
  .el-form .el-row .el-col {
    margin-bottom: 10px;
  }
}
</style>
